// SMTopTabBar.m
#import "SMTopTabBar.h"
@interface SMTopTabBar ()
@property(nonatomic, strong) NSArray<UIButton *> *buttons;
@property(nonatomic, strong) UIView *indicator;
@property(nonatomic, assign) NSInteger selectedIndex;
@end
@implementation SMTopTabBar
- (instancetype)initWithTitles:(NSArray<NSString *> *)titles {
    if (self=[super initWithFrame:CGRectZero]) {
        self.backgroundColor = UIColor.systemBackgroundColor;
        NSMutableArray *btns = [NSMutableArray array];
        [titles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *b = [UIButton buttonWithType:UIButtonTypeSystem];
            [b setTitle:obj forState:UIControlStateNormal];
            b.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
            [b setTitleColor:UIColor.labelColor forState:UIControlStateNormal];
            b.tag = idx;
            [b addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:b];
            [btns addObject:b];
        }];
        self.buttons = btns;
        self.indicator = [UIView new];
        self.indicator.backgroundColor = [UIColor colorWithRed:0.23 green:0.56 blue:0.96 alpha:1.0];
        self.indicator.layer.cornerRadius = 1.0;
        [self addSubview:self.indicator];
        self.selectedIndex = 0;
    }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat w = self.bounds.size.width / MAX(self.buttons.count, 1);
    CGFloat h = self.bounds.size.height;
    [self.buttons enumerateObjectsUsingBlock:^(UIButton * _Nonnull b, NSUInteger idx, BOOL * _Nonnull stop) {
        b.frame = CGRectMake(w*idx, 0, w, h-2);
    }];
    [self updateIndicatorAnimated:NO];
}
- (void)tap:(UIButton *)sender {
    [self setSelectedIndex:sender.tag animated:YES];
    if ([self.delegate respondsToSelector:@selector(topTabBarDidSelectIndex:)]) {
        [self.delegate topTabBarDidSelectIndex:sender.tag];
    }
}
- (void)setSelectedIndex:(NSInteger)index animated:(BOOL)animated {
    _selectedIndex = index;
    [self.buttons enumerateObjectsUsingBlock:^(UIButton * _Nonnull b, NSUInteger idx, BOOL * _Nonnull stop) {
        b.alpha = (idx==index) ? 1.0 : 0.6;
    }];
    [self updateIndicatorAnimated:animated];
}
- (void)updateIndicatorAnimated:(BOOL)animated {
    if (self.buttons.count==0) return;
    UIButton *b = self.buttons[self.selectedIndex];
    CGRect target = CGRectMake(b.frame.origin.x + (b.bounds.size.width-28)/2.0, self.bounds.size.height-2, 28, 2);
    if (animated) [UIView animateWithDuration:0.20 animations:^{ self.indicator.frame = target; }];
    else self.indicator.frame = target;
}
@end
